/*********************************************************************\
*
*                  (c) lkc
*                  All Rights Reserved. lkc Confidential
*
\*********************************************************************/
/*********************************************************************\
*   Title                      :
*
*   Module Description         :
*
*   Author                     : lkc
*
*   Created                    : 2019-3-10
*
\*********************************************************************/


#include <string>
#include "PwmUserspace.h"
#include "UtilityTH.h"

Pwm::Pwm(int chipIndex, int pwmIndex)
    :m_chipIndex(chipIndex),
      m_pwmIndex(pwmIndex)
{
    init();
}

int Pwm::ExportPwmChip() const
{
    char fileNameEnable[50];
    sprintf(fileNameEnable,"/sys/class/pwm/pwmchip%d/pwm0/enable",m_chipIndex);
    FILE *fp = fopen(fileNameEnable,"r");
    if(fp != nullptr)
    {
        printf("pwmchip%d has been exported\n",m_chipIndex);
        fclose(fp);
        return -1;
    }
    char fileNameExport[50];
    sprintf(fileNameExport,"/sys/class/pwm/pwmchip%d/export",m_chipIndex);
    MyWrite(fileNameExport,"w","0");

    printf("/sys/class/pwm/pwmchip%d/export\n",m_chipIndex);
    return 1;
}

void Pwm::init() const
{
    ExportPwmChip();
    SetEnable(true);
}

int Pwm::SetEnable(bool isEnable) const
{
    char fileName[50];
    sprintf(fileName,"/sys/class/pwm/pwmchip%d/pwm%d/enable",m_chipIndex,m_pwmIndex);
    std::string content = isEnable?"1":"0";
    MyWrite(fileName,"w",content.c_str());
    return 1;
}

void Pwm::SetCycleTime(long time)
{
    m_cycleTime = time;
    char fileName[50];
    sprintf(fileName,"/sys/class/pwm/pwmchip%d/pwm%d/period",m_chipIndex,m_pwmIndex);
    char timeStr[50];
//    printf("period time set %ld\n",m_cycleTime);
    sprintf(timeStr,"%ld",m_cycleTime);
    MyWrite(fileName,"w",timeStr);
}

void Pwm::SetOnTime(long time)
{
    m_onTime = time;
    char fileName[50];
    sprintf(fileName,"/sys/class/pwm/pwmchip%d/pwm%d/duty_cycle",m_chipIndex,m_pwmIndex);
    char timeStr[50];
//    printf("duty_cycle time set %ld\n",m_onTime);
    sprintf(timeStr,"%ld",m_onTime);
    MyWrite(fileName,"w",timeStr);
}

Pwm::~Pwm()
{
    SetEnable(false);
}





/********************************************************************\
 *
 * REVISION RECORDS
 *
\*********************************************************************/
/*********************************************************************/
/*
 *
 *
 *
\*********************************************************************/
/*------------------------------The End------------------------------*/
